package com.yy.base.servlet;

import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpSession;
import com.mes.entity.User;
import com.yy.base.util.UserUtil;

@SuppressWarnings("unchecked")
public class UserListener {
	private static Map<Object, HttpSession> map = new HashMap();
	/**
	 * session创建时调用
	 */
	public static void sessionCreated(HttpSession session) {
		User user = (User)session.getAttribute(UserUtil.USERSESSION);
		if (user != null) {
			try {
				HttpSession session1 = map.get(user.getId());
				if (session1 != session && session1 != null) {
					//session1.invalidate();
				}
			} catch (Exception e) {
			}
			//map.put(user.getId(), session);
		}
	}

	/**
	 * session创建时调用
	 */
	public static void sessionDistroy(HttpSession session) {
		User user = (User)session.getAttribute(UserUtil.USERSESSION);
		if (user != null) {
			try {
				HttpSession session1 = map.get(user.getId());
				if (session1 != session && session1 != null) {
					map.remove(user.getId());
					session1.invalidate();
				}
			} catch (Exception e) {
			}
		}
	}
	
	/**
	 * 销毁过期session
	 */
	public static int getSessionSize() {
		int size = 0;
		try {
			HttpSession session = null;
			for (Object key : map.keySet()) {
				session = map.get(key);
				if (session == null) {
					map.remove(key);
				} else {
					User user = (User)session.getAttribute(UserUtil.USERSESSION);
					if (user != null) {
						map.remove(key);
					} else {
						size ++;
					}
				}
			}
		} catch (Exception e) {
		}
		return size;
	}
}